from machine import I2S, Pin
from lib.config.index import sensor_config
from lib.log.index import exception_logger
from lib.net.index import http
import sys

"""
MAX98357功放
"""
class Max98357:
    def __init__(self, sck_pin, ws_pin, sd_pin, i2s_num = 0):
        self.__sck = sck_pin
        self.__ws = ws_pin
        self.__sd = sd_pin
        self.__i2s = i2s_num
        self.__audio = None

        self.init()

    def init(self):
        """
            sd -- DIN
            sck --- BCLK
            ws -- LRC
            GND -- GND
            5V或3.3V -- VCC
            """
        if self.__audio:
            return

        self.__audio = I2S(
            self.__i2s,
            sck=Pin(self.__sck),
            ws=Pin(self.__ws),
            sd=Pin(self.__sd),
            mode=I2S.TX,
            bits=16,
            format=I2S.MONO,
            rate=8000,
            ibuf=20000,
        )

    def play_bytes(self, audio_bytes):
        if sensor_config.is_debug():
            print("音频长度:", len(audio_bytes))
        data_view = memoryview(audio_bytes)
        while True:
            play_data = data_view[0:1024]
            data_view = data_view[1024:]
            num_read = len(play_data)

            if num_read == 0:
                break

            num_written = 0
            while num_written < num_read:
                num_written += self.__audio.write(play_data[num_written:num_read])
        if sensor_config.is_debug():
            print("播放结束.")


    def play_wav_file(self, file_name):
        if sensor_config.is_debug():
            print(f"开始播放 {file_name}")
        with open(file_name, "rb") as f:
            audio_data = f.read()
            audio_data = audio_data[44:]
            self.play_bytes(audio_data)


    def network_play(self, text):
        """联网播放文本"""
        response = None
        try:
            response = http.POST(
                "http://www.hanxiaoxin.cn:8080/tts",
                {
                    "Text": text,
                    "Codec": "wav",
                    "EmotionCategory": "poetry",
                    "VoiceType": 301000,
                    "mime": "wav",
                },
                "raw",
            )

            while True:
                read_data = response.raw.read(1024 * 20)
                if not read_data:
                    break

                if sensor_config.is_debug():
                    from utils import common
                    print("读取大小: ", len(read_data))
                    common.print_gc_info()
                self.play_bytes(read_data)
        except Exception as e:
            exception_logger.log(e)
            response and response.close()


if __name__ == "__main__":
    from lib.net.index import wlan
    wlan.connect()
    max98357 = Max98357(8,9,10)
    max98357.network_play("我们的目标是没有蛀牙！")
